package xiaodou.services
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;
	
	import xiaodou.core.controls.Loading;
	import xiaodou.services.enums.HttpResutEnum;

	public class HttpRequest implements IRequest
	{
		private var _loader:URLLoader;
		private var _completeFunction:Function;
		private var _errorFunction:Function;
		private var _autoDealFail:Boolean;
		
		/**
		 * 实例化
		 * @param completeFunction 请求完成的处理函数，格式为fun(data:Object);
		 * @param errorFunction 请求失败的处理函数，格式为fun(data:Object, errorMessage:String)
		 * @param dealFail 是否自动处理返回结果为data.result == HttpResutEnum.FAIL的情况
		 * 
		 */		
		public function HttpRequest(completeFunction:Function, errorFunction:Function = null, autoDealFail:Boolean = true)
		{	
			_completeFunction = completeFunction;
			_errorFunction = errorFunction;
			_autoDealFail = autoDealFail;
		}
		
		public function request(url:String):void
		{
			if(_loader == null)
			{
				_loader = new URLLoader();
				_loader.addEventListener(Event.COMPLETE, loader_completeHandler);
				_loader.addEventListener(IOErrorEvent.IO_ERROR, loader_ioErrorHandler);
				_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_securityErrorHandler);
			}
			cancel();
			_loader.load(new URLRequest(url));
			Loading.instance.show();
			
		}
		
		protected function loader_securityErrorHandler(event:SecurityErrorEvent):void
		{
			Loading.instance.hide();
			if(_errorFunction != null)
				_errorFunction(event.text);
			else
				Alert.show(event.text);

		}
		
		protected function loader_ioErrorHandler(event:IOErrorEvent):void
		{
			Loading.instance.hide();
			if(_errorFunction != null)
				_errorFunction(_loader.data, event.text);
			else
				Alert.show(event.text);
		}
		
		protected function loader_completeHandler(event:Event):void
		{
			Loading.instance.hide();
			var obj:Object = JSON.parse(_loader.data);
			if(obj.result == HttpResutEnum.FAIL && _autoDealFail)
				Alert.show(obj.message);
			else if(_completeFunction != null)
				_completeFunction(obj);
		}		
		
		public function cancel():void
		{
			try
			{
				_loader.close();
			} 
			catch(error:Error) 
			{
				
			}
		}
		
		public function set completeFunction(value:Function):void
		{
			_completeFunction = value;
		}
		
		public function get completeFunction():Function
		{
			return _completeFunction;
		}
		
		public function get errorFunction():Function
		{
			return _errorFunction;
		}
		
		public function set errorFunction(value:Function):void
		{
			_errorFunction = value;
		}
		
	}
}